package com.yuandengta.yomall.seckill.interceptor;

import com.yuandengta.common.constant.AuthConstant;
import com.yuandengta.common.vo.MemberVO;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器 {@link LoginInterceptor}
 *
 * @author Kevin
 * @email: 178676392@qq.com
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberVO> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean match = antPathMatcher.match("/seckill", uri);
        if (!match) {
            return true;
        }

        MemberVO memberVO = (MemberVO) request.getSession().getAttribute(AuthConstant.SESSION_LOGIN_USER);
        if (memberVO == null) {
            // 没有登录
            response.sendRedirect("http://auth.yomall.com/login.html");
            return false;
        }

        threadLocal.set(memberVO);

        return true;
    }
}
